/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.builder;

import com.jb.framework.PersistentManager;
import com.jb.web.application.Command;
import com.jb.web.bean.UIComponentImpl;
import com.jb.web.bean.WebTreeNode;
import com.jb.web.bean.event.UIEvent;
import com.jb.web.bean.event.UIEventHandler;
import com.jb.web.context.WebContext;

import com.jb.faces.component.ActionSource;


/**
 * System command manager for menu command
 */
public class CommandManager implements UIEventHandler {
    public void handleEvent(WebContext pCtx, UIEvent event) {
        if (!(pCtx.getSession().getSelected() instanceof WebTreeNode)) {
            return;
        }

        UIComponentImpl comp = (UIComponentImpl) event.getSource();
        WebTreeNode node = (WebTreeNode) pCtx.getSession().getSelected();

        if (comp instanceof ActionSource) {
            String command = ((Command) comp).getCommand();

            if ("paste".equals(command)) {
                pCtx.getSession().getClipboard().paste(pCtx, node);
            } else if ("export".equals(command)) {
            } else if ("toggleEditor".equals(command)) {
                UIComponentImpl editor = (UIComponentImpl) comp.getPage().getDescendantByClientId("editorPanel");

                if (editor != null) {
                    String states = editor.getVisible();
                    editor.setVisible("" + "false".equals(states));
                }
            } else if ("save".equals(command)) {
                PersistentManager pm = pCtx.getSession().getPersistentManager();
                pm.save(node.getRootNode());
            } else if ("copy".equals(command)) {
                pCtx.getSession().getClipboard().copy(pCtx, node);
            } else if ("delete".equals(command)) {
                if (node.getParent() instanceof WebTreeNode) {
                    node.getParent().getChildren().remove(node);
                    node.delete(pCtx);
                }
            }
        }
    }
}
